package com.example.administrator.smarthome_androids;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUnderstander;
import com.iflytek.cloud.SpeechUnderstanderListener;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.TextUnderstander;
import com.iflytek.cloud.TextUnderstanderListener;
import com.iflytek.cloud.UnderstanderResult;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    protected EditText mEdtxt;
    protected Button mBtn1;
    protected Button mBtn2;
    protected EditText mEdtxtTotext;
    protected Button mBtn3;
    protected EditText mEdtxtResult;
    protected Button mBtn4;
    protected EditText mEdtxtTextResult;
    private SpeechSynthesizer mTts;
    private SpeechRecognizer mIat;
    private RecognizerDialog mDialog;
    private String mStrs;
    private SpeechUnderstander mSpeechUnderstande;
    private TextUnderstander mTextUnderstander;
    private StringBuffer mResultBuffer;
    String TAG = "hello";

    private String mTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_main);
        SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID + "=5940d3f3");
        initView();
    }

    public void DB(View v) {
        Intent in = new Intent(this, DBActivity.class);
        startActivity(in);
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn1) {
            //语音合成
            String str = mEdtxt.getText().toString();
            TextToSpe(str);
        } else if (view.getId() == R.id.btn2) {
            //语音识别
            SpeechsToText();
            //  SpeToText(this);
        } else if (view.getId() == R.id.btn3) {
            //语音语义理解

            SpeechStander();
        } else if (view.getId() == R.id.btn4) {
            TextSpeechStander();
        }
    }

    //文本语义理解
    private void TextSpeechStander() {
        mEdtxtTextResult.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s)) {
                    Toast.makeText(MainActivity.this, "请输入文字", Toast.LENGTH_SHORT).show();
                } else {
                    mStrs = mEdtxtTextResult.getText().toString();
                }
            }
        });

        mTextUnderstander = TextUnderstander.createTextUnderstander(this, null);
        if (mTextUnderstander.isUnderstanding()) {
            mTextUnderstander.cancel();
            Toast.makeText(this, "取消", Toast.LENGTH_SHORT).show();
        } else {
            int ret = mTextUnderstander.understandText(mStrs, mTextUnderstanderListener);
            if (ret != 0) {
                Toast.makeText(this, "文本语义理解失败", Toast.LENGTH_SHORT).show();
            }
        }


    }


    private TextUnderstanderListener mTextUnderstanderListener = new TextUnderstanderListener() {

        @Override
        public void onResult(final UnderstanderResult result) {

            String mTextAns = "";
            if (null != result) {
                // 显示
                String resultString = result.getResultString();

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(resultString);

                    //返回的响应吗
                    int rc = jsonObject.optInt("rc");
                    //发出的命令
                    String order = jsonObject.optString("text");
                    Log.e("llllll", resultString);
                    Log.e("order", order);
                    switch (rc) {
                        case 0:
                            // TODO: 2017/6/19 0019 逻辑处理
                            //首先判断是自定义的技能，还是官方的技能
                            //DEVICE.open"自己定义的技能,"light_smartHome"官方技能
                            String service = jsonObject.optString("service");
                            //截取后四位做比较

                            String substring = service.substring(service.length() - 4, service.length());
                            //设备
                            Log.e(TAG, service);
                            Log.e(TAG, substring);
                            if (substring.equals("Home")) {
                                JSONObject semantic = jsonObject.optJSONObject("semantic");
                                JSONObject slots = semantic.optJSONObject("slots");
                                Log.e(TAG, slots + "");
                                //开关类型
                                String attrValue = slots.optString("attrValue");
                                Log.e(TAG, attrValue);
                                JSONObject location = slots.optJSONObject("location");
                                //房间
                                String room = "";
                                if (location != null) {
                                    room = location.optString("room");
                                    Log.e(TAG, room);
                                }

                                JSONObject datetime = slots.optJSONObject("datetime");
                                //时间，格式为22：00：00
                                if (datetime != null) {
                                    mTime = datetime.optString("time", "");
                                    Log.e(TAG, mTime);
                                }
                                //所有
                                String modifier = slots.optString("modifier");
                                Log.e(TAG, modifier);
                                String GUAN = "关";
                                String ROOM = "主卧";
                                String DEVICE = "airControl_smartHome";
                                if (GUAN.equals(attrValue) && ROOM.equals(room) && DEVICE.equals(service)) {
                                    Log.e(TAG, "关闭主卧空调的命令已经发出111111");
                                }
                                if ("开".equals(attrValue) && ROOM.equals(room) && DEVICE.equals(service)) {
                                    Log.e(TAG, "打开主卧空调的命令已经发出");
                                }
                                if ("22:00:00".equals(mTime) && GUAN.equals("关") && "light_smartHome".equals(service) && "所有".equals(modifier)) {
                                    Log.e(TAG, "关闭所有的灯命令已发出");
                                }
                                if ("开".equals("开") && "light_smartHome".equals(service) && "所有".equals(modifier)) {
                                    Log.e(TAG, "打开所有的灯命令已发出");
                                }


                              /*  List<OpenBean> openBeen = DBManager.getDaoSession(MainActivity.this).getOpenBeanDao().queryBuilder()
                                        .where(OpenBeanDao.Properties.MString.eq("light_smartHome")).where(OpenBeanDao.Properties.Type.eq("开"))
                                        .where(OpenBeanDao.Properties.Location.eq("主卧")).list();
                                if (openBeen.size() > 0) {
                                    if (openBeen.get(0).getMString().equals(service) && openBeen.get(0).getMString().equals(room) && openBeen.get(0).getMString().equals(attrValue)) {
                                        // TODO: 2017/6/20 0020  发送命令打开主卧室的灯
                                        Log.e("命令", "命令已发出");
                                    }
                                } else {
                                    Toast.makeText(MainActivity.this, "您发出的命令无法识别", Toast.LENGTH_SHORT).show();
                                }

                                Log.e("设备", openBeen + "");*/
                            }
                            if (substring.equals("open")) {
                                Gson gson = new Gson();
                                RoomBean roombean = gson.fromJson(resultString, RoomBean.class);
                                //开关
                                String value = roombean.getMoreResults().get(0).getSemantic().getSlots().getAttrValue();
                                Log.e(TAG, value);
                                //房间
                                String room = roombean.getMoreResults().get(0).getSemantic().getSlots().getLocation().getRoom();
                                Log.e(TAG, room);
                                //设备名称
                                String service1 = roombean.getMoreResults().get(0).getService();
                                Log.e(TAG, service1);
                                if ("开".equals(value) && "主卧".equals(room) && "light_smartHome".equals(service1)) {
                                    Log.e(TAG, "打开主卧的灯的命令已经发出");
                                }
                                if ("关".equals(value) && "主卧".equals(room) && "light_smartHome".equals(service1)) {
                                    Log.e(TAG, "关闭次卧的灯的命令已经发出");
                                }

                                if ("开".equals(value) && "次卧".equals(room) && "light_smartHome".equals(service1)) {
                                    Log.e(TAG, "打开次卧的灯的命令已经发出");
                                }
                                if ("关".equals(value) && "次卧".equals(room) && "light_smartHome".equals(service1)) {
                                    Log.e(TAG, "关闭次卧的灯的命令已经发出");
                                }
                            }


                        case 4:
                            Toast.makeText(MainActivity.this, "您的命令无法被识别，请您重试", Toast.LENGTH_LONG).show();
                            break;
                    }


                    JSONObject mAnswer = jsonObject.getJSONObject("answer");
                    mTextAns = mAnswer.getString("text");


                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (!TextUtils.isEmpty(mTextAns)) {
                    mEdtxtTextResult.setText(mTextAns);
                    TextToSpe(mTextAns);
                }
            } else {
                Log.d("", "understander result:null");
                Toast.makeText(MainActivity.this, "语义识别不正确", Toast.LENGTH_SHORT).show();
            }
        }


        @Override
        public void onError(SpeechError error) {
            // 文本语义不能使用回调错误码14002，请确认您下载sdk时是否勾选语义场景和私有语义的发布

        }
    };

    //语义理解
    private void SpeechStander() {
        mSpeechUnderstande = SpeechUnderstander.createUnderstander(this, null);
        mSpeechUnderstande.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mSpeechUnderstande.setParameter(SpeechConstant.DOMAIN, "iat");
        mSpeechUnderstande.setParameter(SpeechConstant.NLP_VERSION, "3.0");
        mSpeechUnderstande.setParameter(SpeechConstant.RESULT_TYPE, "json");
        SpeechUnderstanderListener speechUnderstanderListener = new SpeechUnderstanderListener() {


            @Override
            public void onVolumeChanged(int i, byte[] bytes) {
                //  Toast.makeText(MainActivity.this,"当前正在说话，音量大小：" +i ,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onBeginOfSpeech() {

                Toast.makeText(MainActivity.this, "开始说话", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEndOfSpeech() {

                Toast.makeText(MainActivity.this, "结束说话", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResult(UnderstanderResult understanderResult) {
                String resultString = understanderResult.getResultString();
                String mTextAns = "";
                JSONObject mAnswer;
                try {
                    JSONObject jsonObject = new JSONObject(resultString);
                    //返回的响应吗
                    int rc = jsonObject.optInt("rc");
                    //发出的命令
                    String order = jsonObject.optString("text");
                    Log.e("llllll", resultString);
                    Log.e("order", order);
                    switch (rc) {
                        case 0:
                            // TODO: 2017/6/19 0019 逻辑处理
                            //首先判断是自定义的技能，还是官方的技能
                            //DEVICE.open"自己定义的技能,"light_smartHome"官方技能
                            String service = jsonObject.optString("service");
                            //截取后四位做比较

                            String substring = service.substring(service.length() - 4, service.length());
                            //设备
                            Log.e(TAG, service);
                            Log.e(TAG, substring);
                            if (substring.equals("Home")) {
                                JSONObject semantic = jsonObject.optJSONObject("semantic");
                                JSONObject slots = semantic.optJSONObject("slots");
                                Log.e(TAG, slots + "");
                                //开关类型
                                String attrValue = slots.optString("attrValue");
                                Log.e(TAG, attrValue);
                                JSONObject location = slots.optJSONObject("location");
                                //房间
                                String room = "";
                                if (location != null) {
                                    room = location.optString("room");
                                    Log.e(TAG, room);
                                }

                                JSONObject datetime = slots.optJSONObject("datetime");
                                //时间，格式为22：00：00
                                if (datetime != null) {
                                    mTime = datetime.optString("time", "");
                                    Log.e(TAG, mTime);
                                }
                                //所有
                                String modifier = slots.optString("modifier");
                                Log.e(TAG, modifier);
                                String GUAN = "关";
                                String ROOM = "主卧";
                                String DEVICE = "airControl_smartHome";
                                if (GUAN.equals(attrValue) && ROOM.equals(room) && DEVICE.equals(service)) {
                                    Log.e(TAG, "关闭主卧空调的命令已经发出111111");
                                }
                                if ("开".equals(attrValue) && ROOM.equals(room) && DEVICE.equals(service)) {
                                    Log.e(TAG, "打开主卧空调的命令已经发出");
                                }
                                if ("22:00:00".equals(mTime) && GUAN.equals("关") && "light_smartHome".equals(service) && "所有".equals(modifier)) {
                                    Log.e(TAG, "关闭所有的灯命令已发出");
                                }
                                if ("开".equals("开") && "light_smartHome".equals(service) && "所有".equals(modifier)) {
                                    Log.e(TAG, "打开所有的灯命令已发出");
                                }


                              /*  List<OpenBean> openBeen = DBManager.getDaoSession(MainActivity.this).getOpenBeanDao().queryBuilder()
                                        .where(OpenBeanDao.Properties.MString.eq("light_smartHome")).where(OpenBeanDao.Properties.Type.eq("开"))
                                        .where(OpenBeanDao.Properties.Location.eq("主卧")).list();
                                if (openBeen.size() > 0) {
                                    if (openBeen.get(0).getMString().equals(service) && openBeen.get(0).getMString().equals(room) && openBeen.get(0).getMString().equals(attrValue)) {
                                        // TODO: 2017/6/20 0020  发送命令打开主卧室的灯
                                        Log.e("命令", "命令已发出");
                                    }
                                } else {
                                    Toast.makeText(MainActivity.this, "您发出的命令无法识别", Toast.LENGTH_SHORT).show();
                                }

                                Log.e("设备", openBeen + "");*/
                            }
                            if (substring.equals("open")) {
                                Gson gson = new Gson();
                                RoomBean roombean = gson.fromJson(resultString, RoomBean.class);
                                //开关
                                String value = roombean.getMoreResults().get(0).getSemantic().getSlots().getAttrValue();
                                Log.e(TAG, value);
                                //房间
                                String room = roombean.getMoreResults().get(0).getSemantic().getSlots().getLocation().getRoom();
                                Log.e(TAG, room);
                                //设备名称
                                String service1 = roombean.getMoreResults().get(0).getService();
                                Log.e(TAG, service1);
                                if ("开".equals(value) && "主卧".equals(room) && "light_smartHome".equals(service1)) {
                                    Log.e(TAG, "打开主卧的灯的命令已经发出");
                                }
                                if ("关".equals(value) && "主卧".equals(room) && "light_smartHome".equals(service1)) {
                                    Log.e(TAG, "关闭次卧的灯的命令已经发出");
                                }

                                if ("开".equals(value) && "次卧".equals(room) && "light_smartHome".equals(service1)) {
                                    Log.e(TAG, "打开次卧的灯的命令已经发出");
                                }
                                if ("关".equals(value) && "次卧".equals(room) && "light_smartHome".equals(service1)) {
                                    Log.e(TAG, "关闭次卧的灯的命令已经发出");
                                }
                            }


                        case 4:
                            Toast.makeText(MainActivity.this, "您的命令无法被识别，请您重试", Toast.LENGTH_LONG).show();
                            break;
                    }


                    mAnswer = jsonObject.getJSONObject("answer");
                    //返回值
                    mTextAns = mAnswer.getString("text");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mEdtxtResult.setText(mTextAns);
                Log.e(TAG, mTextAns);
                TextToSpe(mTextAns);
            }

            @Override
            public void onError(SpeechError speechError) {
                Toast.makeText(MainActivity.this, "语义理解error=" + speechError.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {
            }
        };
        //开始语义理解
        mSpeechUnderstande.startUnderstanding(speechUnderstanderListener);
    }


    //语音转换为文本
    private void SpeechsToText() {

        mIat = SpeechRecognizer.createRecognizer(MainActivity.this, null);
        mDialog = new RecognizerDialog(this, null);
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");


        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");

        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");
        boolean isShowDialog = true;
        if (isShowDialog) {
            //显示对话框
            mDialog.setListener(mRecognizerDialogListener);
            mDialog.show();
            Toast.makeText(MainActivity.this, "请开始说话", Toast.LENGTH_SHORT).show();
        } else {
            // 不显示听写对话框
            int ret = mIat.startListening(mRecognizerListener);
            if (ret != ErrorCode.SUCCESS) {

                Toast.makeText(MainActivity.this, "听写失败,错误码：" + ret, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "请开始说话", Toast.LENGTH_SHORT).show();
            }
        }


    }

    /**
     * 听写监听器。
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
            Toast.makeText(MainActivity.this, "开始说话", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(SpeechError error) {
            // Tips：
            // 错误码：10118(您没有说话)，可能是录音机权限被禁，需要提示用户打开应用的录音权限。
            // 如果使用本地功能（语记）需要提示用户开启语记的录音权限。

        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            // Toast.makeText(MainActivity.this, "结束说话", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            Log.d(TAG, results.getResultString());
            printResult(results);

           /* if (isLast) {


                final String result = parseVoice(results.getResultString());
                mEdtxtTotext.setText(result);
            }*/
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {

            Toast.makeText(MainActivity.this, "当前正在说话，音量大小：" + volume, Toast.LENGTH_SHORT).show();
            Log.d(TAG, "返回音频数据：" + data.length);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
        }
    };

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {

            printResult(results);

        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {

        }

    };


    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<>();

    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());

        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        mIatResults.put(sn, text);

        mResultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            mResultBuffer.append(mIatResults.get(key));
        }
        String speech = mResultBuffer.toString();
        mEdtxtTotext.setText(speech);
        // TODO: 2017/6/15 0015 模糊检索数据库,通过这句话和数据库里面的值做出比较
        // ,如果搜索到数据库中的命令词句所包含客户说出的内容，则发出相应的命令，否则提示用户命令失败
        List<OpenBean> openBeen = DBUtils.queryByStr(this, speech);
        //假如数据库里面没有用户所说的命令词，则openBeen为null
        Log.e(TAG, openBeen + "");//E/bbbbbbbbbbb: []

        if (openBeen.size() <= 0) {
            Toast.makeText(this, "暂时没有匹配到您所发出的命令,请您说的详细一些", Toast.LENGTH_SHORT).show();
        } else {
            // TODO: 2017/6/16 0016 发出相应的命令
            Toast.makeText(this, openBeen + "", Toast.LENGTH_SHORT).show();
            Log.e(TAG, openBeen + "");
        }
    }


    //语音合成,文字转换为语音
    private void TextToSpe(String str) {
        //1.创建SpeechSynthesizer对象, 第二个参数：本地合成时传InitListener
        mTts = SpeechSynthesizer.createSynthesizer(this, null);
        //2.合成参数设置，详见《科大讯飞MSC API手册(Android)》SpeechSynthesizer 类
        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");//设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速
        mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量，范围0~100
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
        //设置合成音频保存位置（可自定义保存位置），保存在“./sdcard/iflytek.pcm”
        //保存在SD卡需要在AndroidManifest.xml添加写SD卡权限
        //如果不需要保存合成音频，注释该行代码,获取保存录音时的时间作为唯一id，保存到数据库中
        //  mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
        //3.开始合成


        // TODO: 2017/6/14 0014 str需要换成从本地检索出所需要的文本
        mTts.startSpeaking(str, new SynthesizerListener() {
            //播放进度回调
            //percent为播放进度0~100,beginPos为播放音频在文本中开始位置，endPos表示播放音频在文本中结束位置.
            @Override
            public void onSpeakBegin() {
                Toast.makeText(MainActivity.this, "开始阅读", Toast.LENGTH_SHORT).show();
            }

            //缓冲进度回调
            //percent为缓冲进度0~100，beginPos为缓冲音频在文本中开始位置，endPos表示缓冲音频在文本中结束位置，info为附加信息。
            @Override
            public void onBufferProgress(int i, int i1, int i2, String s) {
                //Log.i(TAG, "onBufferProgress: AAAAAA" + i);
            }

            @Override
            public void onSpeakPaused() {

            }

            @Override
            public void onSpeakResumed() {

            }

            @Override
            public void onSpeakProgress(final int i, int i1, int i2) {

            }

            //会话结束回调接口，没有错误时，error为null
            @Override
            public void onCompleted(SpeechError speechError) {
                //  Toast.makeText(MainActivity.this, "阅读结束", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {

            }
        });

    }


    private void initView() {
        mEdtxt = (EditText) findViewById(R.id.edtxt);
        mBtn1 = (Button) findViewById(R.id.btn1);
        mBtn1.setOnClickListener(MainActivity.this);
        mBtn2 = (Button) findViewById(R.id.btn2);
        mBtn2.setOnClickListener(MainActivity.this);
        mEdtxtTotext = (EditText) findViewById(R.id.edtxt_totext);
        mBtn3 = (Button) findViewById(R.id.btn3);
        mBtn3.setOnClickListener(MainActivity.this);
        mEdtxtResult = (EditText) findViewById(R.id.edtxt_result);
        mBtn4 = (Button) findViewById(R.id.btn4);
        mBtn4.setOnClickListener(MainActivity.this);
        mEdtxtTextResult = (EditText) findViewById(R.id.edtxt_text_result);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTts != null) {

            mTts.destroy();
            mTts = null;
        }

        if (mSpeechUnderstande != null) {
            // 退出时释放连接
            mSpeechUnderstande.cancel();
            mSpeechUnderstande.destroy();

        }

        if (null != mTextUnderstander) {
            if (mTextUnderstander.isUnderstanding())
                mTextUnderstander.cancel();
            mTextUnderstander.destroy();
        }
    }


}
